<?php
/**
 * Created by PhpStorm.
 * User: j28981
 * Date: 2015/9/1
 * Time: 13:55
 * me_user表的控制器，向这里发起的部分请求用ajax
 */
class userAction extends Action{
    private static $fields = array('user_id'=>'编号ID','user_name'=>'用户名','user_role'=>'角色');
    public function __construct(){
       Db::dbInstall(); //所有的方法都要操作数据库，自动连接数据库
    }
    public function listOp(){
        $field = isset($_POST['search_field'])?$_POST['search_field']:'';
        $value = isset($_POST['field_value'])?trim($_POST['field_value']):'';

        $model = new userModel();
        $list = $model->getALL($field,$value);
        if(isset($_POST['search'])){
            //由ajax查询时而来
            include_once TPLS_DIR.DS."user_search_tpl.php";
            exit;
        }
        $fields = self::$fields;
        include_once TEMPLATES_DIR.DS."user_list.php";
    }

    /**
     *添加第一步用get,第二步用post,返回可以用echo 或 include
     */
    public function addOp(){
        if(isset($_POST['add2'])){
            //ajax请求
            $name = $_POST['name'];
            $pwd = $_POST['pwd'];
            $role = $_POST['role'];
            $model = new userModel();

            if($model->addUser($name,$pwd,$role)){
                echo json_encode(array('state'=>1,'msg'=>'添加成功'));
            }else{
                echo json_encode(array('state'=>0,'msg'=>'添加失败'));
            }
        }else{
            include_once TEMPLATES_DIR.DS."user_add.php";

        }
    }
    public function editOp(){
        if(isset($_POST['edit2'])){
            //ajax请求修改
            $name = $_POST['name'];
            $pwd = $_POST['pwd'];
            $role = $_POST['role'];
            $id = $_POST['user_id'];
            if(userModel::updateUser($name,$pwd,$role,$id)){
                echo json_encode(array('state'=>1,'msg'=>'编辑成功'));
            }else{
                echo json_encode(array('state'=>0,'msg'=>'编辑失败'));
            }
        }else{
            $id = $_GET['user_id'];
            $sql = "select * from #__user where user_id='$id'";
            $user_row = Db::queryRow($sql);
            include_once TEMPLATES_DIR.DS."user_edit.php";

        }
    }
    public function delOp(){

        $user_id = $_GET['user_id'];
        if(Db::Delete("delete from #__user where user_id='$user_id'")){
            echo 'true';
        }else{
            echo 'false';
        }
    }

}